//
//  DJQrcodeViewController.m
//  WeiboDemo
//
//  Created by Bworm on 15/1/31.
//  Copyright (c) 2015年 Bworm. All rights reserved.
//

#import "DJQrcodeViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface DJQrcodeViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *qrcodeConsY;

@property (nonatomic, weak) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) CADisplayLink *link;
- (IBAction)close:(id)sender;
@end

@implementation DJQrcodeViewController

- (void)viewDidLoad
{
    // 创建定时器
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
    [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    self.link = link;
    
    
    // 1.创建输入设备
    AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 2.根据输入设备创建输入对象
    AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc] initWithDevice:inputDevice error:nil];
    // 3.创建输出对象
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    // 4.设置输出对象的代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    // 5.创建会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    _session = session;
    // 6.将输入和输出添加到会话中
    if ([session canAddInput:input]) {
        [session addInput:input];
    }
    if ([session canAddOutput:output]) {
        [session addOutput:output];
    }
    // 7.设置输出的数据类型
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    // 8.设置预览界面
    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    previewLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:previewLayer atIndex:0];
    _previewLayer = previewLayer;
    // 9.开始采集数据
    [session startRunning];
}

- (void)update
{
    self.qrcodeConsY.constant -= 5;
    if (self.qrcodeConsY.constant <= -170) {
        self.qrcodeConsY.constant = 170;
    }
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        [self.session stopRunning];
    }
    [self.previewLayer removeFromSuperlayer];
    AVMetadataMachineReadableCodeObject *obj = [metadataObjects lastObject];
    
    [self.link invalidate];
    self.link = nil;
    
    UILabel *label = [[UILabel alloc] initWithFrame:self.view.bounds];
    label.numberOfLines = 0;
    label.text = obj.stringValue;
    [self.view addSubview:label];
}

- (IBAction)close:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
